from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from app import db
from app.models.user import User
import re

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    
    # 验证必填字段
    if not data.get('username') or not data.get('password'):
        return jsonify({'message': '用户名和密码为必填项'}), 400
    
    # 检查用户名是否已存在
    if User.query.filter_by(username=data['username']).first():
        return jsonify({'message': '用户名已存在'}), 400
    
    # 检查手机号是否已存在
    if data.get('phone') and User.query.filter_by(phone=data['phone']).first():
        return jsonify({'message': '手机号已存在'}), 400
    
    # 检查邮箱是否已存在
    if data.get('email') and User.query.filter_by(email=data['email']).first():
        return jsonify({'message': '邮箱已存在'}), 400
    
    # 检查昵称是否已存在
    if data.get('nickname') and User.query.filter_by(nickname=data['nickname']).first():
        return jsonify({'message': '昵称已存在'}), 400
    
    # 创建新用户
    try:
        user = User(
            username=data['username'],
            password=data['password'],
            nickname=data.get('nickname'),
            phone=data.get('phone'),
            email=data.get('email')
        )
        db.session.add(user)
        db.session.commit()
        
        return jsonify({
            'message': '注册成功',
            'user': user.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'注册失败: {str(e)}'}), 500

@auth_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    
    if not data:
        return jsonify({'message': '无效的请求数据'}), 400
    
    # 获取登录凭证和密码
    credential = data.get('credential')
    password = data.get('password')
    
    if not credential or not password:
        return jsonify({'message': '登录凭证和密码为必填项'}), 400
    
    # 根据凭证类型查找用户
    user = None
    
    # 判断凭证类型（用户名、手机号或邮箱）
    if re.match(r'^1[3-9]\d{9}$', credential):  # 手机号格式
        user = User.query.filter_by(phone=credential).first()
    elif re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', credential):  # 邮箱格式
        user = User.query.filter_by(email=credential).first()
    else:  # 默认为用户名
        user = User.query.filter_by(username=credential).first()
    
    # 验证用户和密码
    if user and user.verify_password(password):
        access_token = create_access_token(identity=user.id)
        return jsonify({
            'message': '登录成功',
            'access_token': access_token,
            'user': user.to_dict()
        }), 200
    
    return jsonify({'message': '用户名或密码错误'}), 401

@auth_bp.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    return jsonify(user.to_dict()), 200

@auth_bp.route('/change-password', methods=['PUT'])
@jwt_required()
def change_password():
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    data = request.get_json()
    
    if not data.get('old_password') or not data.get('new_password'):
        return jsonify({'message': '原密码和新密码为必填项'}), 400
    
    # 验证原密码
    if not user.verify_password(data['old_password']):
        return jsonify({'message': '原密码输入不正确'}), 400
    
    # 验证新密码不能与原密码相同
    if data['old_password'] == data['new_password']:
        return jsonify({'message': '新密码不能与原密码一致'}), 400
    
    # 更新密码
    user.password = data['new_password']
    db.session.commit()
    
    return jsonify({'message': '密码修改成功'}), 200